package cn.simple.manager.configuration;

import cn.simple.manager.exception.DataSourceKeyNotFountException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DynamicDataSourceHolder implements ApplicationContextAware {
    private static final ThreadLocal<String> holder = new ThreadLocal<String>();
    static DynamicDataSourceConfiguration dynamicDataSourceConfiguration;
    public static void setHolder(String key){
        if(!dynamicDataSourceConfiguration.getDruid().containsKey(key)){
            throw new DataSourceKeyNotFountException("未找到key所对应的数据库");
        }
        holder.set(key);
    }
    public static String getHolder(){
      return holder.get();
    }
    public static void clear(){
        holder.remove();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        dynamicDataSourceConfiguration = applicationContext.getBean(DynamicDataSourceConfiguration.class);
    }
}
